package com.qcu.controller.admin;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.qcu.annotation.LimitRate;
import com.qcu.annotation.RequireAuthorization;
import com.qcu.entity.SystemMenu;
import com.qcu.exception.RepeatException;
import com.qcu.service.SystemMenuService;
import com.qcu.util.Response;
import com.qcu.util.ResponseCode;
import com.qcu.util.ThreadLocalUtil;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Name: MyComputer
 * @ClassName SystemMenuController
 * @Description: 管理员对系统菜单的增删改查
 * @date 2025/2/6 11:50
 */

@RestController
@RequestMapping("/admin/systemMenu")
public class SystemMenuController {

    @Resource
    private SystemMenuService systemMenuService;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 保存系统菜单
     * @param systemMenu 系统菜单对象
     * @return 响应结果
     */
    @PostMapping("/save")
    @RequireAuthorization({"ADMIN"})
    public Response save(@RequestBody SystemMenu systemMenu)throws RepeatException {
        try {
            boolean save = systemMenuService.save(systemMenu);
            return save ? Response.success() : Response.failure(ResponseCode.FAILURE, "保存失败");
        } catch (Exception e) {
            throw new RepeatException(e.getMessage());
        }
    }

    /**
     * 更新系统菜单
     * @param systemMenu 系统菜单对象
     * @return 响应结果
     */
    @PutMapping("/update")
    @RequireAuthorization({"ADMIN"})
    public Response update(@RequestBody SystemMenu systemMenu) {
        systemMenu.setUpdatedAt(null);
        boolean update = systemMenuService.updateById(systemMenu);
        return update ? Response.success() : Response.failure(ResponseCode.FAILURE, "更新失败");
    }

    /**
     * 删除系统菜单
     * @param id 系统菜单ID
     * @return 响应结果
     */
    @DeleteMapping("/remove/{id}")
    @RequireAuthorization({"ADMIN"})
    public Response remove(@PathVariable Integer id) {
        boolean remove = systemMenuService.removeById(id);
        return remove ? Response.success() : Response.failure(ResponseCode.FAILURE, "删除失败");
    }

    /**
     * 获取所有系统菜单
     * @return 响应结果
     */
    @GetMapping("/get")
    @LimitRate(key = "getSystemMenu",permitsPerSecond = 1500,expire = 12,msg = "八嘎雅鹿，你滴点那么快滴干什么滴干活...")
//    @RequireAuthorization({"ADMIN","PLAIN","STAFF","USER"}) // 所有人都可以获得系统菜单
    public Response get() {
        // 获取当前用户角色
//        Map<String,Object> o = ThreadLocalUtil.get();
//        String role = (String) o.get("role");
//        // 初始化条件构造器
//        LambdaQueryWrapper<SystemMenu> systemMenuLambdaQueryWrapper = null;
//        String o1 = (String) redisTemplate.opsForValue().get("menuOfSystem");
//
//        if (!role.equals("ADMIN")){
//            if (o1 != null){
//                List<SystemMenu> list = JSON.parseArray(o1, SystemMenu.class);
//                List<SystemMenu> collect = list.stream().filter(systemMenu -> systemMenu.getRole().equals(role)).collect(Collectors.toList());
//                return Response.success(collect);
//            }
//            systemMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            systemMenuLambdaQueryWrapper.eq(SystemMenu::getState, 0).eq(SystemMenu::getRole, role);
//
//        }else if (role.equals("ADMIN") && o1 != null){
//            return Response.success(JSON.parseArray(o1, SystemMenu.class));
//        }
//
//        List<SystemMenu> list = systemMenuService.list(systemMenuLambdaQueryWrapper);
//        redisTemplate.opsForValue().set("menuOfSystem", JSON.toJSONString(list),60, TimeUnit.MINUTES);
//        return Response.success(list);


        String o1 = (String) redisTemplate.opsForValue().get("menuOfSystem");

        if (o1 != null){
            Map<String,Object> o = ThreadLocalUtil.get();
            String role = (String) o.get("role");
            List<SystemMenu> list = JSON.parseArray(o1, SystemMenu.class);
            List<SystemMenu> collect = list.stream().filter(systemMenu -> systemMenu.getRole().equals(role)).collect(Collectors.toList());
            return Response.success(collect);
        }
        Map<String,Object> o = ThreadLocalUtil.get();
        String role = (String) o.get("role");
        LambdaQueryWrapper<SystemMenu> systemMenuLambdaQueryWrapper = null;
        if (!role.equals("ADMIN")){
            systemMenuLambdaQueryWrapper = new LambdaQueryWrapper<>();
            systemMenuLambdaQueryWrapper.eq(SystemMenu::getState, 0).eq(SystemMenu::getRole, role);
        }
        List<SystemMenu> list = systemMenuService.list(systemMenuLambdaQueryWrapper);

        String s = JSON.toJSONString(list);
        redisTemplate.opsForValue().set("menuOfSystem", s,60, TimeUnit.MINUTES);

        return Response.success(list);
    }
}
